<?php
/**
 * @author qingyu8@staff.weibo.com
 * @date 2018/07/01
 */
namespace api\modules\v1\controllers;

use Yii;
use yii\web\Controller;

class WechatController extends Controller {
    public $enableCsrfValidation = false;

    public function actionIndex() {
        /* @var $app \EasyWeChat\OfficialAccount\Application */
        $app = Yii::$app->wechat->app;
        $app->server->push(function($message) {
            Yii::info($message, __METHOD__);
            switch ($message['MsgType']) {
                case 'event':
                    switch ($message['Event']) {
                        case 'subscribe':
                            return '蟹蟹关注，么么哒';
                            break;
                    }
                    break;
                case 'text':
                    return '机器人这厢有礼了，人工客服将会尽快联系您';
                    break;
            }
        });
        $response = $app->server->serve();
        $response->send();
    }

    /**
     * 通过code换openid
     */
    public function actionCodeOpenid() {
        //        $frontPaghe=urlencode('https://qingyu.me');
        //        $redirect_uri=urlencode("https://www.cooldive.com.cn/api/v1/wechat/code-openid?frontpage=$frontPaghe");
        //        echo "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd8ceb2101c9078a6&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";exit;
        //        require_once Yii::$app->vendorPath . "/WxpayAPI_php_v3.0.1/example/WxPay.JsApiPay.php";$tools = new \JsApiPay();
        //        $openId = $tools->GetOpenid();
        //        var_dump($openId);
        /* @var $app \EasyWeChat\OfficialAccount\Application */
        $app = Yii::$app->wechat->app;
        $oauth = $app->oauth;

        // 获取 OAuth 授权结果用户信息
        $user = $oauth->user()->toArray();
        Yii::info($user, 'debug' . __METHOD__);
        $openid = $user['openid'] ?? $user['original']['openid'];
        Yii::$app->session->set('wechat_openid', $openid);
        $frontpageInfo = parse_url($_GET['frontpage']);
        if (YII_ENV_PROD) {
            //$frontpageInfo['host'];
        }
        header('location:' . $_GET['frontpage']);
    }
}
